<?php
/**
 * @Author:      zy
 * @DateTime:  2018-05-07
 * @Description: 更新 orders 和 car_wash_order 两张表中 reception 字段的历史数据
 */
$api_service_path = __DIR__ . "/../../../api/";

ob_start();
require_once($api_service_path . "public/index.php");
ob_end_clean();
DB::connection()->disableQueryLog(); 
$sc_user_arr = sc_user_arr();

//------------替换订单接车人------------
$replace_count = 0; //替换的条数
$sql = "select * from(select * from order_flows  where type='sc' ORDER BY order_id ASC,created_at ASC) as  a GROUP BY  order_id";
$count_sql =  DB::select("select count(id) as count from (select id from order_flows  where type='sc'  GROUP BY  order_id) as a");
$count = $count_sql[0]->count;

$page = 0;
$page_size = 1000;
for ($page=0;$page<=ceil($count/$page_size);$page++ ) {
    $start = $page*$page_size;
    $select_sql = $sql." limit $start,$page_size ";
    $list = DB::select("$select_sql");
    foreach($list as $_list){
        //echo $_list->order_id . "\n";
        $user_name = isset($sc_user_arr[$_list->user_id]) ? $sc_user_arr[$_list->user_id]:"";
        DB::table('orders')
          ->where('order_id', $_list->order_id)
          ->update(['reception_id' => $_list->user_id,"reception_name"=>$user_name]);
        $replace_count ++;
    }
}
print_r("ok! orders replace over. count:$count,replace:$replace_count" . "\n");

//------------替换洗车单接车人------------
$replace_count = 0;
$sql = "select * from(select * from car_wash_order_flow where type='sc' ORDER BY order_id ASC,created_at ASC ) as  a GROUP BY  order_id";
$count_sql =  DB::select("select count(id) as count from (select id from car_wash_order_flow  where type='sc'  GROUP BY  order_id) as a");
$count = $count_sql[0]->count;

$page = 0;
$page_size = 1000;
for ($page=0;$page<=ceil($count/$page_size);$page++ ) {
    $start = $page*$page_size;
    $select_sql = $sql." limit $start,$page_size ";
    $list = DB::select("$select_sql");
    foreach($list as $_list){
        //echo $_list->order_id . "\n";
        $user_name = isset($sc_user_arr[$_list->user_id]) ? $sc_user_arr[$_list->user_id]:"";
        DB::table('car_wash_order')
          ->where('order_id', $_list->order_id)
          ->update(['reception_id' => $_list->user_id,"reception_name"=>$user_name]);
        $replace_count ++;
    }
}

print_r("ok! car_wash_order replace over. count:$count,replace:$replace_count" . "\n");


function sc_user_arr() {
    $user_list= SCUser::get();
    $user_arr = [];
    foreach($user_list as $v) {
        $user_arr[$v->id] = $v->real_name;
    }
    return $user_arr;
}